// import {
//   MQTTClient,
//   MQTTOptionsType,
//   EVENTID
// } from '../mqtt/mqtt.ets';
// import emitter from '@ohos.events.emitter';
import {
  VehicleReportMessage,
  DeviceControlPayload,
  IncomingMqttMessage
} from '../mqtt/MqttTypes';
// import { MQTTClient } from '../mqtt/mqtt.ets';
import Globle from './Globle';
import  globleInstance from '../services/Globle'

// const MQTT_TOPIC = 'Hi3861_Service_000';

// 创建一个只包含所需方法的轻量级接口
interface MqttPushClient {
  pushMessage(data: string, topic: string): Promise<void>;
}

// CarStatus interface needs to be exported
export interface CarStatus {
  speed?: number;
  rpm?: number;
  fuelLevel?: number;
  engineTemp?: number;
  mileage?: number;
  lightsOn?: boolean;
  doorsLocked?: boolean;
  // 新增 vehicle 结构，包含CarDashboard.ets用到的所有属性
  vehicle?: {
    speed?: number;
    pedals?: {
      throttle?: number;
      brake?: number;
    };
    steering?: {
      angle?: number;
    };
    lights?: {
      headlights?: boolean;
      positionLights?: boolean;
      highBeam?: boolean;
      fogLights?: boolean;
      hazard?: boolean;
    };
    wipers?: {
      enabled?: boolean;
      speed?: 'slow' | 'medium' | 'fast' | 'auto';
      rearWiper?: boolean;
    };
    seats?: {
      driverPosition?: number;
      driverHeight?: number;
      driverBackrest?: number;
      driverHeating?: boolean;
      driverVentilation?: boolean;
    };
    airConditioner?: {
      enabled?: boolean;
      temperature?: number;
      fanSpeed?: number;
      mode?: 'auto' | 'manual' | 'eco';
    };
  };
}

export interface VoiceCommand {
  text: string;
  intent: string;
  entities: Record<string, any>;
  confidence: number;
}

// 环境传感器状态接口
export interface EnvironmentStatus {
  temperature: number;
  humidity: number;
  airQuality: number;
  fire: number;
  fanStatus: string;
}

export class CarControlService {
  private static instance: CarControlService;
  private carStatus: CarStatus = {
    speed: 60,
    rpm: 2200,
    fuelLevel: 75,
    engineTemp: 90,
    mileage: 12345,
    lightsOn: false,
    doorsLocked: true,
    vehicle: {
      speed: 60,
      pedals: {
        throttle: 0,
        brake: 0
      },
      steering: {
        angle: 0
      },
      lights: {
        headlights: false,
        positionLights: false,
        highBeam: false,
        fogLights: false,
        hazard: false
      },
      wipers: {
        enabled: false,
        speed: 'auto',
        rearWiper: false
      },
      seats: {
        driverPosition: 50,
        driverHeight: 50,
        driverBackrest: 30,
        driverHeating: false,
        driverVentilation: false
      },
      airConditioner: {
        enabled: false,
        temperature: 22,
        fanSpeed: 3,
        mode: 'auto'
      }
    }
  };
  private listeners: (() => void)[] = [];
  private mqttClient: MqttPushClient | null = null;
  private environmentStatus: EnvironmentStatus = {
    temperature: 0,
    humidity: 0,
    airQuality: 0,
    fire: 0,
    fanStatus: 'OFF'
  };
  private environmentListeners: (() => void)[] = [];

  private constructor() {
  }

  // 新增：用于从外部注入MQTT客户端
  setMqttClient(client: MqttPushClient): void {
    this.mqttClient = client;
  }

  public static getInstance(): CarControlService {
    if (!CarControlService.instance) {
      CarControlService.instance = new CarControlService();
    }
    return CarControlService.instance;
  }

  // 处理接收到的MQTT消息 (修改为公开方法)
  public handleMqttMessage(message: IncomingMqttMessage): void {
    // 使用类型守卫来安全地处理不同类型的消息
    if ('topic' in message && message.topic === 'vehicle_report') {

      // 解析油门、刹车、方向盘
      if (this.carStatus.vehicle) {
        console.info('MQTT vehicle_report steering_wheel 原始值:', message.data.steering_wheel);
        console.info('MQTT vehicle_report accelerator 原始值:', message.data.accelerator);
        console.info('MQTT vehicle_report brake 原始值:', message.data.brake);
        globleInstance.setAngle(message.data.steering_wheel)
        globleInstance.setAccelerator(message.data.accelerator)
        globleInstance.setBrake(message.data.brake)

        this.carStatus = { ...this.carStatus };
      }
      this.notifyStatusChange();
    } else if ('services' in message) {
      // 解析环境板2（Fan）
      const fanService = message.services.find(s => s.service_id === 'Fan');
      if (fanService) {
        this.environmentStatus = {
          temperature: fanService.properties.Temperature,
          humidity: fanService.properties.Humidity,
          airQuality: fanService.properties.Air_Quality,
          fire: fanService.properties.Fire,
          fanStatus: fanService.properties.FanStatus
        };
        this.notifyEnvironmentChange();
      }
    }
  }

  // 获取当前车机状态
  public getCarStatus(): CarStatus {
    return { ...this.carStatus };
  }

  // 添加状态监听器
  addStatusListener(listener: () => void): void {
    this.listeners.push(listener);
  }

  // 移除状态监听器
  removeStatusListener(listener: () => void): void {
    const index = this.listeners.indexOf(listener);
    if (index > -1) {
      this.listeners.splice(index, 1);
    }
  }

  // 通知状态变化
  private notifyStatusChange(): void {
    this.listeners.forEach(listener => listener());
  }

  // 更新踏板状态（用于显示）
  updatePedalStatus(throttle: number, brake: number, clutch: number = 0): void {
    this.carStatus.speed = Math.max(0, Math.min(100, throttle));
    this.carStatus.rpm = Math.max(0, Math.min(8000, brake));
    this.notifyStatusChange();
  }

  // 更新方向盘角度（用于显示）
  updateSteeringAngle(angle: number): void {
    this.carStatus.speed = Math.max(-450, Math.min(450, angle));
    this.notifyStatusChange();
  }

  // 执行来自知识库的动作
  public executeAction(action: string, parameters: any): string {
    switch (action) {
      case 'set_temperature':
        const temp = parameters.temperature;
        return `空调温度已设置为 ${temp} 度`;
      case 'toggle_lights':
        this.carStatus.lightsOn = !this.carStatus.lightsOn;
        return `车灯已${this.carStatus.lightsOn ? '打开' : '关闭'}`;
      case 'toggle_locks':
        this.carStatus.doorsLocked = !this.carStatus.doorsLocked;
        return `车门已${this.carStatus.doorsLocked ? '锁定' : '解锁'}`;
      default:
        return `无法识别的指令: ${action}`;
    }
  }

  // 获取车辆状态报告
  public getVehicleStatusReport(): string {
    return `当前车速 ${this.carStatus.speed} 公里/小时，引擎转速 ${this.carStatus.rpm} RPM，剩余油量 ${this.carStatus.fuelLevel}%。`;
  }

  // 获取环境信息
  public getEnvironmentInfo(): string {
    return `车外温度 28 度，天气晴朗。`;
  }

  // 新增：灯光控制方法，支持CarDashboard.ets的调用
  public controlVehicle(command: string): void {
    if (!this.carStatus.vehicle || !this.carStatus.vehicle.lights) return;
    let device = '';
    let status = 0;
    switch (command) {
      case 'turn_on_headlights':
        this.carStatus.vehicle.lights.headlights = true;
        device = 'headlight'; status = 1;
        break;
      case 'turn_off_headlights':
        this.carStatus.vehicle.lights.headlights = false;
        device = 'headlight'; status = 0;
        break;
      case 'turn_on_position_lights':
        this.carStatus.vehicle.lights.positionLights = true;
        device = 'position_light'; status = 1;
        break;
      case 'turn_off_position_lights':
        this.carStatus.vehicle.lights.positionLights = false;
        device = 'position_light'; status = 0;
        break;
      case 'turn_on_high_beam':
        this.carStatus.vehicle.lights.highBeam = true;
        device = 'high_beam'; status = 1;
        break;
      case 'turn_off_high_beam':
        this.carStatus.vehicle.lights.highBeam = false;
        device = 'high_beam'; status = 0;
        break;
      case 'turn_on_fog_lights':
        this.carStatus.vehicle.lights.fogLights = true;
        device = 'fog_light'; status = 1;
        break;
      case 'turn_off_fog_lights':
        this.carStatus.vehicle.lights.fogLights = false;
        device = 'fog_light'; status = 0;
        break;
      case 'turn_on_hazard':
        this.carStatus.vehicle.lights.hazard = true;
        device = 'hazard_light'; status = 1;
        break;
      case 'turn_off_hazard':
        this.carStatus.vehicle.lights.hazard = false;
        device = 'hazard_light'; status = 0;
        break;
      default:
        // 未知命令不处理
        break;
    }
    // 发送MQTT消息
    if (device && this.mqttClient) {
      const payload = {
        topic: 'powerseat_detect',
        device: device,
        status: status
      };
      this.mqttClient.pushMessage(JSON.stringify(payload), 'Hi3861_Service_000');
    }
    this.notifyStatusChange();
  }

  // 新增：雨刮控制方法
  public controlWipers(command: string, value?: any): void {
    if (!this.carStatus.vehicle || !this.carStatus.vehicle.wipers) return;
    let device = '';
    let status = 0;
    switch (command) {
      case 'turn_on':
        this.carStatus.vehicle.wipers.enabled = true;
        device = 'wiper'; status = 1;
        break;
      case 'turn_off':
        this.carStatus.vehicle.wipers.enabled = false;
        device = 'wiper'; status = 0;
        break;
      case 'set_speed':
        this.carStatus.vehicle.wipers.speed = value;
        // 可选：可扩展为不同device
        break;
      case 'rear_on':
        this.carStatus.vehicle.wipers.rearWiper = true;
        // 可选：可扩展为rear_wiper
        break;
      case 'rear_off':
        this.carStatus.vehicle.wipers.rearWiper = false;
        // 可选：可扩展为rear_wiper
        break;
      default:
        break;
    }
    if (device && this.mqttClient) {
      const payload = {
        topic: 'powerseat_detect',
        device: device,
        status: status
      };
      this.mqttClient.pushMessage(JSON.stringify(payload), 'Hi3861_Service_000');
    }
    this.notifyStatusChange();
  }

  // 新增：座椅控制方法
  public controlSeats(seat: string, command: string, value?: any): void {
    if (!this.carStatus.vehicle || !this.carStatus.vehicle.seats) return;
    if (seat !== 'driver') return; // 目前只支持驾驶座
    let device = '';
    let status = 0;
    switch (command) {
      case 'set_position':
        this.carStatus.vehicle.seats.driverPosition = value;
        // 绝对位置控制
        this.sendSeatPosition('set_position', value, this.carStatus.vehicle.seats.driverHeight || 0);
        break;
      case 'set_height':
        this.carStatus.vehicle.seats.driverHeight = value;
        this.sendSeatPosition('set_position', this.carStatus.vehicle.seats.driverPosition || 0, value);
        break;
      case 'set_backrest':
        this.carStatus.vehicle.seats.driverBackrest = value;
        // 可选：如需MQTT控制靠背，可扩展
        break;
      case 'heating_on':
        this.carStatus.vehicle.seats.driverHeating = true;
        device = 'heater'; status = 1;
        break;
      case 'heating_off':
        this.carStatus.vehicle.seats.driverHeating = false;
        device = 'heater'; status = 0;
        break;
      case 'ventilation_on':
        this.carStatus.vehicle.seats.driverVentilation = true;
        device = 'fan'; status = 1;
        break;
      case 'ventilation_off':
        this.carStatus.vehicle.seats.driverVentilation = false;
        device = 'fan'; status = 0;
        break;
      default:
        break;
    }
    if (device && this.mqttClient) {
      const payload = {
        topic: 'powerseat_detect',
        device: device,
        status: status
      };
      this.mqttClient.pushMessage(JSON.stringify(payload), 'Hi3861_Service_000');
    }
    this.notifyStatusChange();
  }

  // 新增：空调控制方法
  public controlAirConditioner(command: string, value?: any): void {
    if (!this.carStatus.vehicle || !this.carStatus.vehicle.airConditioner) return;
    switch (command) {
      case 'turn_on':
        this.carStatus.vehicle.airConditioner.enabled = true;
        break;
      case 'turn_off':
        this.carStatus.vehicle.airConditioner.enabled = false;
        break;
      case 'set_temperature':
        this.carStatus.vehicle.airConditioner.temperature = value;
        break;
      case 'increase_temperature':
        this.carStatus.vehicle.airConditioner.temperature = (this.carStatus.vehicle.airConditioner.temperature || 22) + 1;
        break;
      case 'decrease_temperature':
        this.carStatus.vehicle.airConditioner.temperature = (this.carStatus.vehicle.airConditioner.temperature || 22) - 1;
        break;
      case 'set_fan_speed':
        this.carStatus.vehicle.airConditioner.fanSpeed = value;
        break;
      case 'set_mode':
        this.carStatus.vehicle.airConditioner.mode = value;
        break;
      default:
        break;
    }
    this.notifyStatusChange();
  }

  // 新增：座椅绝对位置控制
  public sendSeatPosition(command: 'set_position' | 'reset', horizontal: number, vertical: number): void {
    if (this.mqttClient) {
      const payload = {
        topic: 'power_seat_pos_cmd',
        command: command,
        horizontal: horizontal,
        vertical: vertical
      };
      this.mqttClient.pushMessage(JSON.stringify(payload), 'Hi3861_Service_000');
    }
  }

  // 新增：车窗控制
  public sendWindowControl(action: 'full_open' | 'full_close' | 'stop' | 'partly_open' | 'partly_close'): void {
    if (this.mqttClient) {
      const payload = {
        topic: 'power_window_cmd',
        action: action
      };
      this.mqttClient.pushMessage(JSON.stringify(payload), 'Hi3861_Service_000');
    }
  }

  // 注册环境状态监听器
  public addEnvironmentListener(listener: () => void): void {
    this.environmentListeners.push(listener);
  }

  private notifyEnvironmentChange(): void {
    this.environmentListeners.forEach(listener => listener());
  }

  public getEnvironmentStatus(): EnvironmentStatus {
    return { ...this.environmentStatus };
  }
} 